package sgd.tp2.server.net.udp;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;

import sgd.tp2.api.cdr.CDR;
import sgd.tp2.api.logging.Log;
import sgd.tp2.api.net.CDRFormatType;
import sgd.tp2.api.net.CEPType;

public class UDPServerObject extends UDPServer {

	public UDPServerObject(CDRFormatType cdrFormatType, int port, CEPType cepType) {
		super(cdrFormatType, port, cepType);
	}

	public UDPServerObject(CDRFormatType cdrFormatType, int port, CEPType cepType, int packetSize) {
		super(cdrFormatType, port, cepType, packetSize);
	}

	@Override
	public void run() {

		byte[] receivedData = new byte[packetSize];
		DatagramPacket packet = new DatagramPacket(receivedData, receivedData.length);

		while (running) {

			// Esperar mensagem
			try {
				serverSocket.receive(packet);
				
				receivedCDR();

			} catch (IOException e) {
				Log.infoln("");
				Log.warningln("Parou de receber. Servidor terminado");
				stopServer();
				break;
			}

			handleObject(packet);
		}
	}

	public void handleObject(DatagramPacket packet) {
		startCDRHandling();

		ObjectInputStream inStream = null;
		CDR cdr = null;
		try {
			inStream = new ObjectInputStream(new ByteArrayInputStream(packet.getData()));
			cdr = (CDR) inStream.readObject();
		} catch (IOException e) {
			Log.errorln("Leitura do stream de entrada de mensagens {0}: {1}", cdrFormatType,
					e.getMessage());
			stopServer();
			return;
		} catch (ClassNotFoundException e) {
			Log.errorln("Impossivel casting do objecto recebido para CDR: {0}", e.getMessage());
		}
		handleCDR(cdr);

		endCDRHandling(cdr);
	}
}
